<?php

class Logging {
    
    private $log_file = '/tmp/logfile.log';
    // define file pointer
    private $fp = null;
    private $filepath = null;

    public function __construct() {
        date_default_timezone_set ("Asia/ShangHai");
        $this->setPath(); // $myVar will now be INITIALIZED
    }

    // set log file (path and name)
    private function setPath() {
        $serverFilePath = $_SERVER["SCRIPT_FILENAME"];
        $doc_dir = strrpos($serverFilePath, '/');
        $doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root

        $this->mkdir_r($doc_dir . '/logs');
        $this->filepath = $doc_dir . '/logs';
    }

    public function mkdir_r($dir, $rights = 0777) {
        if (!is_dir($dir)) {
            $dirs = explode('/', $dir);
            $dir2 = '';
            foreach ($dirs as $part) {
                $dir2.=$part . '/';
                if (!is_dir($dir2) && strlen($dir2) > 0) {
                    mkdir($dir2, 0777);
                }
            }
        }
    }

    public function lfile($filename) {
        $this->log_file = $this->filepath . '/' . $filename;
    }

    // write message to the log file
    public function lwrite($message) {
        // if file pointer doesn't exist, then open log file
        if (!$this->fp)
            $this->lopen();
        // define script name
        $script_name = isset($_SERVER["HTTP_HOST"])?$_SERVER["HTTP_HOST"]:"localhost";
        // define current time
        $time = date('H:i:s');
        // write current time, script name and message to the log file
        fwrite($this->fp, "$time ($script_name) $message\n");
    }

    // open log file
    private function lopen() {
        // define log file path and name
        $lfile = $this->log_file;
        // define the current date (it will be appended to the log file name)
        $today = date('Y-m-d');
        // open log file for writing only; place the file pointer at the end of the file
        // if the file does not exist, attempt to create it
        $this->fp = fopen($lfile . '_' . $today . '.log', 'a') or exit("Can't open $lfile!");
    }

}

?>